﻿using System;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using xuni;

namespace xres
{


    public class FileCopyHandler : DownloadHandlerScript
    {
        public string Err_Write_Out = "Err_Write_Out";
        public string Err_Size = "Err_Size";


        //保存路径
        string _fileSavePath = "";

        string _errType = "";
        public string ErrType { get { return _errType; } }

        FileStream _fs;

        long _totalBytes;
        public long TotalBytes { get { return _totalBytes; } }

        long _haveCopyBytes;
        public long HaveDownBytes { get { return _haveCopyBytes; } }


        public FileCopyHandler(string savePath)
            : base(new byte[8 * 1024])//缓冲大小
        {
            _fileSavePath = savePath;
        }

        protected override void ReceiveContentLength(int contentLength)
        {
            if (false) Debug.Log($"FileCopyHandler: ReceiveContentLength: {IOUtils.Byte2ReadableUnit(contentLength)}, {_fileSavePath}");
            _totalBytes = contentLength;
        }

        protected override float GetProgress()
        {
            return _haveCopyBytes / (float)_totalBytes;
        }

        protected override bool ReceiveData(byte[] data, int len)
        {
            if (data == null || data.Length < 1)
            {
                Debug.Log($"ReceiveData: len: {len}, {_fileSavePath}");
                return false;
            }

            try
            {
                if (null == _fs)
                {
                    _errType = "";

                    var dirPath = Path.GetDirectoryName(_fileSavePath);
                    if (!Directory.Exists(dirPath))
                        Directory.CreateDirectory(dirPath);

                    _fs = File.Open(_fileSavePath, FileMode.OpenOrCreate);
                }

                _fs.Write(data, 0, len);
                _haveCopyBytes += len;
                if (false) Debug.Log($"ReceiveData: RecvLen: {len}, FileLen: {_fs.Length}, Pos: {_fs.Position}");

                return true; //要继续下载
            }
            catch (Exception ex)
            {
                _errType = Err_Write_Out;
                Debug.LogError($"{ex.StackTrace}");

                IOUtils.SafeClose(_fs);
                _fs = null;
            }

            return false;
        }

        protected override void CompleteContent()
        {
            IOUtils.FlushAndClose(_fs);
            _fs = null;

            if (_totalBytes != _haveCopyBytes)
            {
                _errType = Err_Size;
                Debug.Log($"CompleteContent: err size: total:{_totalBytes}, haveCopy:{_haveCopyBytes}, {_fileSavePath}");
            }
            else
            {
                _errType = "";
            }
        }


    } //end of class


}

